import 'dart:async';

import 'package:connectivity/connectivity.dart';
import 'package:dingtalk/core/blocs/chat/chat_bloc.dart';

import 'package:dingtalk/core/values/values.dart';
import 'package:dingtalk/ui/screens/address_list/address_list_screen.dart';
import 'package:dingtalk/ui/screens/discovery/discovery_screen.dart';
import 'package:dingtalk/ui/screens/document/document_screen.dart';
import 'package:dingtalk/ui/screens/message/message_screen.dart';
import 'package:dingtalk/ui/screens/workset/workset_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';

import 'main_drawer_content.dart';

class THMainScreen extends StatefulWidget {
  const THMainScreen({Key key}) : super(key: key);

  @override
  _THMainScreenState createState() => _THMainScreenState();
}

class _THMainScreenState extends State<THMainScreen>
    with AutomaticKeepAliveClientMixin {
  int _selectedIndex = 0;
  List<Widget> _mainBodies = [];

  PageController _mainPageController;

  StreamSubscription<ConnectivityResult> _connectivitySubscription;

  final Connectivity _connectivity = Connectivity();

  @override
  void initState() {
    super.initState();
    _initConnectivity();

    _mainPageController =
        PageController(initialPage: _selectedIndex, keepPage: true);

    _mainBodies
      ..add(THMessageScreen())
      ..add(THDocumentScreen())
      ..add(THWorksetScreen())
      ..add(THAddressListScreen())
      ..add(THDiscoveryScreen());

    _connectivitySubscription =
        _connectivity.onConnectivityChanged.listen(_checkConnectionStatus);
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334);
    super.build(context);
    return Scaffold(
      drawer: Drawer(
        child: THMainDrawerContent(),
      ),
      body: _buildPageView(),
      bottomNavigationBar: buildBottomNavigationBar(),
    );
  }

  Widget buildBottomNavigationBar() {
    return BottomNavigationBar(
      selectedLabelStyle:
          TextStyle(color: kTabSelectedColor, fontSize: kSize22),
      unselectedLabelStyle:
          TextStyle(color: kTabNormalColor, fontSize: kSize22),
      type: BottomNavigationBarType.fixed,
      items: <BottomNavigationBarItem>[
        BottomNavigationBarItem(
            title: Text('消息'),
            icon: SvgPicture.asset(
              'assets/icons/icon_message.svg',
              width: kSize48,
              color: _getBarItemColor(0),
            )),
        BottomNavigationBarItem(
            title: Text('文档'),
            icon: SvgPicture.asset(
              'assets/icons/icon_document.svg',
              width: kSize48,
              color: _getBarItemColor(1),
            )),
        BottomNavigationBarItem(
            title: Text('工作'),
            icon: SvgPicture.asset(
              'assets/icons/icon_workset.svg',
              width: kSize48,
              color: _getBarItemColor(2),
            )),
        BottomNavigationBarItem(
            title: Text('通讯录'),
            icon: SvgPicture.asset(
              'assets/icons/icon_address_list.svg',
              width: kSize48,
              color: _getBarItemColor(3),
            )),
        BottomNavigationBarItem(
            title: Text('发现'),
            icon: SvgPicture.asset(
              'assets/icons/icon_discovery.svg',
              width: kSize48,
              color: _getBarItemColor(4),
            )),
      ],
      currentIndex: _selectedIndex,
      onTap: _onItemTapped,
    );
  }

  PageView _buildPageView() {
    return PageView(
      children: _mainBodies,
      pageSnapping: false,
      physics: NeverScrollableScrollPhysics(),
      controller: _mainPageController,
    );
  }

  Color _getBarItemColor(int currentIndex) {
    return _selectedIndex == currentIndex ? kTabSelectedColor : kTabNormalColor;
  }

  void _onItemTapped(int index) {
    if (index == _selectedIndex) return;
    this.setState(() {
      _selectedIndex = index;
      _mainPageController.jumpToPage(index);
    });
  }

  @override
  void dispose() {
    _connectivitySubscription.cancel();
    super.dispose();
  }

  _initChat() {
    BlocProvider.of<THChatBloc>(context)..add(THChatInitEvent());
  }

  Future<void> _checkConnectionStatus(ConnectivityResult result) async {
    switch (result) {
      case ConnectivityResult.wifi:
      case ConnectivityResult.mobile:
        _initChat();
        break;
      case ConnectivityResult.none:
      default:
        break;
    }
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> _initConnectivity() async {
    ConnectivityResult result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      print(e.toString());
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) {
      return Future.value(null);
    }

    return _checkConnectionStatus(result);
  }

  @override
  bool get wantKeepAlive => true;
}
